﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TanWeb.Models.Entities;
using TanWeb.Helpers;
using TanWeb.Models.DataAccess;
using TanWeb.Controllers.Business.Infrastructure;
using TanWeb.Models.Entities.Master;
using System.Collections;

namespace TanWeb.Controllers.Business
{
    public class MasterBusiness : BaseBusiness
    {
        public bool CheckLogin(string user, string encryptedPassword)
        {
            logger.Info("\tStart Business: Master; Function: CheckLogin");
            MasterDataAccess access = new MasterDataAccess(this.DbContext);
            int masterId = access.GetMasterId(user, encryptedPassword);

            if (masterId <= 0)
            {
                return false;
            }

            Utils.SetSession(Constants.LOGIN_ID, masterId);
            HttpContext.Current.Server.ScriptTimeout = 432000;

            logger.Info("\tEnd Business: Master; Function: CheckLogin");
            return true;
        }

        public int RegisterProduct(string itemGroup, string subItemGroup, UploadedProduct product, string date)
        {
            logger.Info("\tStart Business: Master; Function: RegisterProducts");

            ProductDataAccess access = new ProductDataAccess(this.DbContext);
            int productId = 0;

            try
            {
                productId = access.RegisterProduct(itemGroup, subItemGroup, product, date);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: RegisterProducts");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: RegisterProducts");

            return productId;
        }

        public int RegisterImage(string groupId, string subGroupId, int productId, int imageIndex, string date)
        {
            logger.Info("\tStart Business: Master; Function: RegisterImage");

            ImageDataAccess access = new ImageDataAccess(this.DbContext);
            int result = 0;

            try
            {
                result = access.RegisterImage(groupId, subGroupId, productId, imageIndex, date);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: RegisterImage");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: RegisterImage");

            return result;
        }

        public System.Drawing.Image GetImage(string groupId, string subGroupId, string productId, int imageIndex, string index, string imageType = Constants.TYPE_IMAGE_ORIGINAL)
        {
            logger.Info("\tStart Business: Master; Function: GetImagePath");

            ImageDataAccess access = new ImageDataAccess(this.DbContext);
            System.Drawing.Image image = null;
            List<Image> lstImage = new List<Image>();

            try
            {
                string imageName = null;
                ArrayList fileNameList = (ArrayList)Utils.GetSession(Constants.SESSION_UPLOADED_FILENAME);

                if (groupId != string.Empty && subGroupId != string.Empty && productId != string.Empty)
                {
                    imageName = access.GetImageName(groupId, subGroupId, productId, imageIndex).FirstOrDefault();

                    if (imageName == null)
                    {
                        lstImage = access.GetListImage(groupId, subGroupId, productId);
                        if (imageIndex >= lstImage.Count - 1)
                        {
                            imageName = ((UploadedFile)fileNameList[int.Parse(index) - lstImage.Count - 1]).fileName;
                        }
                    }
                }
                else
                {
                    imageName = ((UploadedFile)fileNameList[imageIndex]).fileName;
                }

                string uploadPath = TanWeb.Helpers.Constants.PATH_UPLOAD_IMAGE.Replace("../", "/");
                string path = System.Web.Hosting.HostingEnvironment.MapPath(uploadPath + imageName);
                image = Utils.GetResizedImage(path, imageType);
                // imagePath = Utils.GetImageUrl(image);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: GetImagePath");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: GetImagePath");
            return image;
        }

        public List<string> GetAllImageThumnail(string groupId, string subGroupId, string productId, string index)
        {
            logger.Info("\tStart Business: Master; Function: GetAllImageThumnail");

            ImageDataAccess access = new ImageDataAccess(this.DbContext);
            List<string> lstImageThumnail = new List<string>();

            try
            {
                List<Image> lstImage = new List<Image>();

                if (groupId != null && subGroupId != null && productId != null)
                {
                    lstImage = access.GetListImage(groupId, subGroupId, productId);
                }

                ArrayList fileNameList = (ArrayList)Utils.GetSession(Constants.SESSION_UPLOADED_FILENAME);

                string uploadPath = TanWeb.Helpers.Constants.PATH_UPLOAD_IMAGE.Replace("../", "/");
                string path = string.Empty;
                int maxId = 0;
                if (lstImage.Count > 0)
                {
                    maxId = lstImage.Last().id;
                }

                if (fileNameList != null)
                {
                    foreach (UploadedFile file in fileNameList)
                    {
                        if (index == null || file.index.Contains(index + ";"))
                        {
                            maxId++;
                            Image img = new Image();
                            img.ImageName = file.fileName;
                            img.id = maxId;
                            lstImage.Add(img);
                        }
                    }
                }
                
                for (int i = 0; i < maxId; i++)
                {
                    lstImageThumnail.Add(string.Empty);
                }

                foreach (Image item in lstImage)
                {
                    path = System.Web.Hosting.HostingEnvironment.MapPath(uploadPath + item.ImageName);
                    System.Drawing.Image image = Utils.GetResizedImage(path, Constants.TYPE_IMAGE_MINIMUM);
                    string imagePath = Utils.GetImageUrl(image);
                    lstImageThumnail[item.id - 1] = imagePath;
                }
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: GetAllImageThumnail");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: GetAllImageThumnail");

            return lstImageThumnail;
        }

        public Product GetProductInfo(string groupId, string subGroupId, string productId)
        {
            logger.Info("\tStart Business: Master; Function: GetProductInfo");

            Product productInfo = null;
            ProductDataAccess access = new ProductDataAccess(this.DbContext);
            groupId = groupId == null ? string.Empty : groupId;
            subGroupId = subGroupId == null ? string.Empty : subGroupId;
            productId = productId == null ? string.Empty : productId;

            try
            {
                if (groupId != string.Empty && subGroupId != string.Empty && productId != string.Empty)
                {
                    productInfo = access.GetProductInfo(groupId, subGroupId, productId);
                }
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: GetProductInfo");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: GetProductInfo");

            return productInfo;
        }

        public List<Image> GetListImage(string groupId, string subGroupId, string productId)
        {
            logger.Info("\tStart Business: Master; Function: GetListImageName");

            List<Image> listImage = new List<Image>();
            ImageDataAccess access = new ImageDataAccess(this.DbContext);

            try
            {
                listImage = access.GetListImage(groupId, subGroupId, productId);

                foreach (Image image in listImage)
                {
                    image.SetTempImagePath();
                }
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: GetListImageName");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: GetListImageName");

            return listImage;
        }

        public int DeleteProduct(string groupId, string subGroupId, string productId)
        {
            logger.Info("\tStart Business: Master; Function: DeleteProduct");

            ImageDataAccess imgAccess = new ImageDataAccess(this.DbContext);
            ProductDataAccess prdAccess = new ProductDataAccess(this.DbContext);
            int result = 0;
            string updateTime = DateTime.Now.ToString(Constants.FORMAT_FULL_DATE_TIME);
            string directoryPath = TanWeb.Helpers.Constants.PATH_UPLOAD_IMAGE.Replace("../", "/");
            string directoryTempPath = TanWeb.Helpers.Constants.PATH_TEMP_IMAGE.Replace("../", "/");

            try
            {
                Utils.DeleteUploadedImages(directoryPath, groupId, subGroupId, productId, directoryTempPath);
                result = imgAccess.DeleteImage(groupId, subGroupId, productId, updateTime);
                result = prdAccess.DeleteProduct(groupId, subGroupId, productId, updateTime);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: DeleteProduct");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: DeleteProduct");

            return result;
        }

        public int DeleteProductsById(List<string> lstId)
        {
            logger.Info("\tStart Business: Master; Function: DeleteProductsById");

            ImageDataAccess imgAccess = new ImageDataAccess(this.DbContext);
            ProductDataAccess prdAccess = new ProductDataAccess(this.DbContext);
            int result = 0;
            string updateTime = DateTime.Now.ToString(Constants.FORMAT_FULL_DATE_TIME);
            // string directoryPath = TanWeb.Helpers.Constants.PATH_UPLOAD_IMAGE.Replace("../", "/");
            // string directoryTempPath = TanWeb.Helpers.Constants.PATH_TEMP_IMAGE.Replace("../", "/");

            try
            {
                // Utils.DeleteUploadedImages(directoryPath, groupId, subGroupId, productId, directoryTempPath);
                // result = imgAccess.DeleteImage(groupId, subGroupId, productId, updateTime);
                result = prdAccess.DeleteProductsById(lstId, updateTime);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: DeleteProductsById");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: DeleteProductsById");

            return result;
        }


        public int DeleteProductsBySubGroupId(List<string> lstId)
        {
            logger.Info("\tStart Business: Master; Function: DeleteProductsBySubGroupId");

            ImageDataAccess imgAccess = new ImageDataAccess(this.DbContext);
            ProductDataAccess prdAccess = new ProductDataAccess(this.DbContext);
            int result = 0;
            string updateTime = DateTime.Now.ToString(Constants.FORMAT_FULL_DATE_TIME);
            // string directoryPath = TanWeb.Helpers.Constants.PATH_UPLOAD_IMAGE.Replace("../", "/");
            // string directoryTempPath = TanWeb.Helpers.Constants.PATH_TEMP_IMAGE.Replace("../", "/");

            try
            {
                // Utils.DeleteUploadedImages(directoryPath, groupId, subGroupId, productId, directoryTempPath);
                // result = imgAccess.DeleteImage(groupId, subGroupId, productId, updateTime);
                result = prdAccess.DeleteProductsBySubGroupId(lstId, updateTime);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: DeleteProductsBySubGroupId");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: DeleteProductsBySubGroupId");

            return result;
        }

        /*
        public int DeleteProducts(List<string> lstId)
        {
            logger.Info("\tStart Business: Master; Function: DeleteProducts");

            ImageDataAccess imgAccess = new ImageDataAccess(this.DbContext);
            ProductDataAccess prdAccess = new ProductDataAccess(this.DbContext);
            int result = 0;
            string updateTime = DateTime.Now.ToString(Constants.FORMAT_FULL_DATE_TIME);
            string directoryPath = TanWeb.Helpers.Constants.PATH_UPLOAD_IMAGE.Replace("../", "/");
            string directoryTempPath = TanWeb.Helpers.Constants.PATH_TEMP_IMAGE.Replace("../", "/");

            try
            {
                Utils.DeleteUploadedImages(directoryPath, groupId, subGroupId, productId, directoryTempPath);
                result = imgAccess.DeleteImage(groupId, subGroupId, productId, updateTime);
                result = prdAccess.DeleteProduct(groupId, subGroupId, productId, updateTime);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: DeleteProducts");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: DeleteProducts");

            return result;
        }
         * */

        public int UpdateProduct(Product p)
        {
            logger.Info("\tStart Business: Master; Function: UpdateProduct");

            ImageDataAccess imgAccess = new ImageDataAccess(this.DbContext);
            ProductDataAccess prdAccess = new ProductDataAccess(this.DbContext);
            string updateTime = DateTime.Now.ToString(Constants.FORMAT_FULL_DATE_TIME);
            int result = 0;

            try
            {
                result = prdAccess.UpdateProduct(p, updateTime);
                result = imgAccess.RegisterImage(p.GroupId.ToString(), p.SubGroupId.ToString(), p.id, 0, updateTime, false);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: UpdateProduct");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: UpdateProduct");

            return result;
        }

        public string RegisterGroup(string groupName, string parentId, string mode)
        {
            logger.Info("\tStart Business: Master; Function: RegisterGroup");

            string result = string.Empty;

            try
            {
                if (mode != null )
                {
                    if (mode == Constants.NEW_GROUP)
                    {
                        ItemGroupDataAccess business = new ItemGroupDataAccess(this.DbContext);
                        result = business.RegisterGroup(groupName);
                    }
                    else if (mode == Constants.NEW_SUB_GROUP)
                    {
                        SubItemGroupDataAccess business = new SubItemGroupDataAccess(this.DbContext);
                        result = business.RegisterSubGroup(parentId, groupName);
                    }
                    else if (mode == Constants.UPDATE_SUB_GROUP)
                    {
                        SubItemGroupDataAccess business = new SubItemGroupDataAccess(this.DbContext);
                        result = business.UpdateSubGroup(parentId, groupName);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: RegisterGroup");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: RegisterGroup");

            return result;
        }

        public string DeleteSubGroup(List<string> arrDel)
        {
            logger.Info("\tStart Business: Master; Function: DeleteSubGroup");

            string result = string.Empty;

            try
            {
                SubItemGroupDataAccess business = new SubItemGroupDataAccess(this.DbContext);
                result = business.DeleteSubGroup(arrDel);
            }
            catch (Exception ex)
            {
                logger.Error("\tError Business: Master; Function: DeleteSubGroup");
                throw ex;
            }

            logger.Info("\tEnd Business: Master; Function: DeleteSubGroup");

            return result;
        }
    }
}